//
//  ChatVideoRightCell.swift
//  Tinsecret_TW
//
//  Created by wanghui on 2018/12/24.
//  Copyright © 2018年 tst. All rights reserved.
//

import UIKit
import Kingfisher
import SwiftyJSON
import AVFoundation

class ChatVideoRightCell: ChatBaseCell {
    
    @IBOutlet weak var imgtopConstraint: NSLayoutConstraint!
    @IBOutlet weak var bgtopConstraint: NSLayoutConstraint!
    @IBOutlet weak var avatar: UIImageView!
    @IBOutlet weak var createTimelabel: WHLabel!
    @IBOutlet weak var namelabel: UILabel!
    @IBOutlet weak var pic: UIImageView!
    
    @IBOutlet weak var activityindicator: UIActivityIndicatorView!
    @IBOutlet weak var sendfailureBtn: UIButton!
    
    @IBOutlet weak var picWidthContraint: NSLayoutConstraint!
    @IBOutlet weak var picHeightContraint: NSLayoutConstraint!
    @IBOutlet weak var videoBtn: UIButton!
    
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        
        self.videoBtn.layer.cornerRadius = self.videoBtn.frame.width / 2
        self.videoBtn.layer.masksToBounds = true
        self.videoBtn.addTarget(self, action: #selector(playAction), for: .touchUpInside)
        
        self.pic.isUserInteractionEnabled = true
        self.addLongPress()
        
        self.selectionStyle = UITableViewCell.SelectionStyle.none
        self.pic.isUserInteractionEnabled = true
        self.pic.clipsToBounds = true
        self.pic.layer.cornerRadius = 5;
        
        self.avatar.isUserInteractionEnabled = true
        let tapAvatar = UITapGestureRecognizer.init(target: self, action: #selector(tapSelector))
        self.avatar.addGestureRecognizer(tapAvatar)
        
        let tapPic = UITapGestureRecognizer.init(target: self, action: #selector(tapPicture))
        self.pic.addGestureRecognizer(tapPic)
        
        let resend = UITapGestureRecognizer.init(target: self, action: #selector(resendMsg))
        self.sendfailureBtn.addGestureRecognizer(resend)
        
        self.createTimelabel.paddingLeft = 5
        self.createTimelabel.paddingRight = 5
        self.createTimelabel.layer.cornerRadius = 5
        self.createTimelabel.layer.masksToBounds = true
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
    
    @objc func tapSelector() {
        print("点击了头像")
    }
    
    @objc func tapPicture() {
//todo
//        delegate?.playVideo(msg: model)
    }
    
    @objc func resendMsg() {
        self.model.status = .pending
        self.layoutSubviews()
        self.delegate?.resend(self.model,cell:self)
    }
    
    override func setup(model: ChatMessage) {
        super.setup(model: model)
        
//        if (UserDefaults.standard.object(forKey: fontCoefficient) != nil) {
//            let contentfontSize = self.getContentFont()
//            let timeFontSize = self.getTimeFont()
//            self.createTimelabel.font = UIFont.systemFont(ofSize: timeFontSize)
//            self.namelabel.font = UIFont.systemFont(ofSize: timeFontSize)
//            //todo
////            self.avatarWidthConstraint.constant = self.getAvatarWidth()
////            self.avatarHeigConstraint.constant = self.getAvatarWidth()
//        }
        
        if let avatar = AppStatusManager.instance.avatar {
            self.avatar.kf.setImage(with: KF.ImageResource(downloadURL: Common.avatarUrl(avatar) ?? URL(string: "localhost")!), placeholder: #imageLiteral(resourceName: "defaultAvatar"),options: [.processor(CryptorProcessor())])
        } else {
            self.avatar.image = #imageLiteral(resourceName: "timg")
        }
        
        if let thumbnail = model.videoThumbnail {
            self.pic.image = thumbnail
            self.picWidthContraint.constant = model.videoWidth
            self.picHeightContraint.constant = model.videoHeight
            
        } else {
            self.pic.backgroundColor = UIColor.white
            self.videoBtn.setImage(UIImage(named: "videoDownload"), for: UIControl.State.normal)
            self.pic.image = UIImage.init(named: "")
            self.picWidthContraint.constant = 65
            self.picHeightContraint.constant = 120
        }

        
        self.pic.contentMode = .scaleAspectFill
        self.createTimelabel.isHidden = !model.showTimeLabel
        self.createTimelabel.text = model.timeStr
        self.namelabel.text = model.fromName
        self.namelabel.isHidden = true
        self.imgtopConstraint.constant = self.createTimelabel.isHidden == true ? 8: 40
        
        if model.status == .pending {
            self.activityindicator.isHidden = false
            self.activityindicator.startAnimating()
        } else {
            self.activityindicator.isHidden = true
            self.activityindicator.stopAnimating()
        }
        self.sendfailureBtn.isHidden = !(model.status == .error)
    }
    
    override func updateUI() {
        super.updateUI()
        DispatchQueue.main.async {
            if self.model.status == .pending {
                self.activityindicator.isHidden = false
                self.activityindicator.startAnimating()
            } else {
                self.activityindicator.isHidden = true
                self.activityindicator.stopAnimating()
            }
            self.sendfailureBtn.isHidden = !(self.model.status == .error)
        }
    }
}

extension ChatVideoRightCell {
    
    @objc func playAction() {
        //如果已下载, 就开始播放, 如果未下载, 就开始下载
        let json = JSON(parseJSON: model.text ?? "")
        print(" == \(json["fileName"].stringValue)")
        let videoFileName = json["fileName"].stringValue
        var url = Common.getLocalUrl(videoFileName, file: "videoUrl")
        if  !FileManager.default.fileExists(atPath: url.path) { //开始下载
            let remoteUrl = Common.videourl(videoFileName)!
            FileDownloadTool.instance.download(remoteUrl, to: url, onFinish: {[unowned self] (filePath) in
                DispatchQueue.main.async {
                    url = remoteUrl
                    self.videoBtn.setImage(UIImage(named: "videoPlay"), for: UIControl.State.normal)
                    //下载完成后, 设置视频第一帧图片
                    //设置视频第一帧图片
                    let videoutil = VideoUtil.instance
                    let image = videoutil.getThumbnailImg(url: url)
                    self.pic.image = image
                    self.model.videoThumbnail = image
                }
            }) { (error) in
                print("\(error)")
            }
        }else {
            delegate?.playVideo(url: url as NSURL)
        }
    }
    
    //长按手势
    @objc func addLongPress() {
        let longPressGes = UILongPressGestureRecognizer.init(target: self, action: #selector(longPressView(_:)))
        //长按等待时间
        longPressGes.minimumPressDuration = 0.5
        
        //长按时候,手指头可以移动的距离
        longPressGes.allowableMovement = 30
        self.pic.addGestureRecognizer(longPressGes)
    }
    
    @objc func longPressView(_ longPressGest:UILongPressGestureRecognizer) {
        if longPressGest.state == UIGestureRecognizer.State.began {
            //长按手势开启
            self.addMenuItem()
        }else {
            
        }
    }
    
    func addMenuItem() {
        self.becomeFirstResponder()
        
        let menuVC = UIMenuController.shared
//        let zhuanfa = UIMenuItem.init(title: "转发", action: #selector(zhuanfaAction))
//        menuVC.menuItems = [zhuanfa]
        
        //长按手势结束
        menuVC.setTargetRect(CGRect.init(x: (self.pic.frame.origin.x + self.pic.frame.size.width * 0.5), y: self.pic.frame.origin.y, width: 0, height: 0), in: self)
        menuVC.setMenuVisible(true, animated: true)
        print("长按触发")
        
    }
    
    override var canBecomeFirstResponder: Bool {
        return true
    }
    
//    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
//        if action == #selector(zhuanfaAction){
//            return true
//        }else if (action == #selector(delete)){
//            return true
//        }
//        return false
//    }
//    //删除
//    @objc override func delete(_ sender: Any?) {
//        print("删除")
//        //删除
//        self.delegate?.deleteDelegate(msg:model)
//    }
//    //举报
//    @objc func reportAction() {
//        print("举报")
//        //举报
//        self.delegate?.reportDelegate(msg:model)
//    }
//    //转发
//    @objc func zhuanfaAction() {
//        self.delegate?.zhuanfaDelegate(msg: model)
//    }
}
